import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', () => {
  const router = useRouter()

  const isAuthenticated = ref(false)
  const user = ref({
    id: null,
    username: '',
    nickname: '',
    avatar: ''
  })

  // 登录方法
  const login = async (phone, password) => {
    try {
      // 调用登录API
      const response = await fetch('http://127.0.0.1:8081/app/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          phone,
          password
        })
      })

      if (!response.ok) {
        throw new Error('登录失败')
      }

      const data = await response.json()
      const token = data.data // 获取返回的token

      // 保存token到localStorage
      localStorage.setItem('access-token', token)

      // 获取用户信息 - 使用正确的token
      const userInfoResponse = await fetch('http://127.0.0.1:8081/app/info', {
        headers: {
          'access-token': token,
          'Content-Type': 'application/json'
        }
      })

      if (!userInfoResponse.ok) {
        throw new Error('获取用户信息失败')
      }

      const userInfo = await userInfoResponse.json()
      const userData = userInfo.data // 获取用户数据

      // 更新状态
      isAuthenticated.value = true
      user.value = {
        id: userData.userId,
        username: userData.username,
        nickname: userData.username, // 如果没有昵称，使用用户名
        avatar: userData.avatarUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      }

      return true
    } catch (error) {
      throw new Error('登录失败: ' + (error.message || '未知错误'))
    }
  }

  // 退出登录
  const logout = async () => {
    try {
      // 清除本地存储的token
      localStorage.removeItem('access-token')

      // 重置状态
      isAuthenticated.value = false
      user.value = {
        id: null,
        username: '',
        nickname: '',
        avatar: ''
      }

      router.push('/')
      return true
    } catch (error) {
      throw new Error('退出登录失败: ' + (error.message || '未知错误'))
    }
  }

// auth.js
const checkAuth = async () => {
  const token = localStorage.getItem('access-token');
  if (token) {
    try {
      const response = await fetch('http://127.0.0.1:8081/app/info', {
        headers: { 'access-token': token }
      });

      if (!response.ok) {
        // 如果 token 无效，清除它
        localStorage.removeItem('access-token');
        return false;
      }

      const userInfo = await response.json();
      console.log('用户信息:', userInfo);

      const userData = userInfo.data;

      // 更新认证状态和用户信息
      isAuthenticated.value = true;
      user.value = {
        id: userData.userId,
        username: userData.username,
        nickname: userData.username,
        avatar: userData.avatarUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      };

      return true;
    } catch (error) {
      console.error('检查认证状态失败:', error);
      return false;
    }
  }
  return false;
};
  return {
    isAuthenticated,
    user,
    login,
    logout,
    checkAuth
  }
})
